<?php

namespace app\admin\controller;
use app\admin\validate\RoomTimeValidate;
use app\models\CampusModel;
use app\models\ClassRoomTimeModel;
use app\models\ClassTimeModel;
use app\models\CompanyModel;
use app\models\GradesModel;
use app\models\UserModel;

/**
 * Class Schooltime
 * @package app\admin\controller
 */
class Schooltime extends Common
{

    /**
     * 用户管理模型.
     *
     *  @var UserModel
     */
    protected $userModel;

    /**
     * 校区管理模型.
     *
     * @var CampusModel
     */
    protected $campusModel;

    /**
     * 上课时间管理模型.
     *
     * @var ClassTimeModel
     */
    protected $classTimeModel;

    /**
     * 班级管理模型.
     *
     * @var GradesModel
     */
    protected $gradesModel;

    /**
     * 上课时间与教室绑定模型.
     *
     * @var ClassRoomTimeModel
     */
    protected $classRoomTimeModel;

    /**
     * 验证.
     *
     * @var RoomTimeValidate
     */
    protected $roomTimeValidate;


    /**
     * 集团模型
     * @var CompanyModel
     */
    protected $companyModel;

    /**
     * 上课时间管理.
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = $this->classTimeModel->getClassTimeLists($param);
            $this->success('success', '', $campus, 0);
        }

        return $this->fetch();
    }

    /**
     * 添加上课时间.
     *
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            //默认为2
            $data['type'] = 2;

            $res_des = $this->time_diff(strtotime($data['start_time']),strtotime($data['end_time']));
            $hours = $res_des['hours'];  //时
            $minutes = $res_des['minutes']; //分
            $seconds = $res_des['seconds']; //秒

            $hours = '0'.$hours;

            if($minutes < 10){
                $minutes = '0'.$minutes;
            }

            if($seconds < 10){
                $seconds = '0'.$seconds;
            }

           $time = $hours.':'.$minutes.':'.$seconds;

            $data['time_long'] = $time;

            /*
            if (!$this->stationValidate->scene('add')->check($data)) {
                $this->error($this->stationValidate->getError(), null, '', 1);
            }
            */
            if (false !== $this->classTimeModel->save($data)) {
                $this->success('添加成功', url('Schooltime/lists'), '', 1);
            }
            $this->error('添加失败', null, '', 1);
        }

        /********添加校区**********/
        $where = [];
        if(get_current_type() == 4 || get_current_type() == 5){/*校区数据权限*/
            $where['id'] = get_current_campus_id();
        }elseif (get_current_type() == 2 || get_current_type() == 3){/*区域数据权限*/
            $where['id'] = ['in',get_current_campus_id()];
        }
        $where['status'] = 1;

        /***********集团**********/
        $company_result = $this->companyModel->select();
        $company_arr =[];
        foreach ($company_result as $key => $value){
            $company_arr[$value['id'].''] = $value['company_name'];
        }
        /*****************************/

        /*************过滤掉未分配系统账号的集团*************/
        if(get_current_type() == 1){  //超管
            $user_result = $this->userModel->where(['wtype' => 2])->select();
            $company_user_arr = [];
            foreach ($user_result as $key => $value){
                $company_user_arr[] = $value['company_id'];
            }
            $company_user_arr = array_unique($company_user_arr);
            $company_user_str = implode(',',$company_user_arr);
            $where['company_id'] = ['in',$company_user_str];
        }

        $campus = $this->campusModel->where($where)->select();
        if(get_current_type() == 1){    //超级管理员
            foreach ($campus as $key => $value){
                $value['campus_name'] =   $value['campus_name'].'【'.$company_arr[$value['company_id'].''].'】';
            }
        }

        return $this->fetch('',['campus' => $campus]);
    }

    /**
     * 编辑上课时间.
     *
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if(strtotime($data['start_time']) >= strtotime($data['end_time'])){
                return ['code' => 1, 'msg' => "开始时间必须小于结束时间"];
            }


            //默认为2
            $data['type'] = 2;

            $res_des = $this->time_diff(strtotime($data['start_time']),strtotime($data['end_time']));
            $hours = $res_des['hours'];  //时
            $minutes = $res_des['minutes']; //分
            $seconds = $res_des['seconds']; //秒

            $hours = '0'.$hours;

            if($minutes < 10){
                $minutes = '0'.$minutes;
            }

            if($seconds < 10){
                $seconds = '0'.$seconds;
            }

            $time = $hours.':'.$minutes.':'.$seconds;

            $data['time_long'] = $time;

            if (!$this->classTimeModel->save($data,['id'=>$data['id']])) {
                $this->error('编辑失败', null, '', 1);
            }
            $this->success('更新成功', url('Schooltime/lists'), '', 1);
        }
    }

    /**
     * 绑定教室及上课时间
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function binding()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $ids = input('ids');
            $ids = explode(',',$ids);
            $class_room = input('id');
            $class_id = input('class_id');
            $data = [];
            foreach ($ids as $id){
                $data['week'] = $id;
                $data['start_time'] = ClassTimeModel::get($id)['start_time'];
                $data['end_time'] = ClassTimeModel::get($id)['end_time'];
                $data['class_room'] = $class_room;
                $data['class_id'] = $class_id;
                ClassRoomTimeModel::create($data);
            }
            $this->success('', '', $class_id, 1);
        }
        $class_room = $this->gradesModel->get(input('id'))['class_room'];
        return $this->fetch('',[
            'id'=>input('id'),
            'class_room'=>$class_room,
            ]);
    }

    /**
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function room()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = $this->classRoomTimeModel->getClassRoomTimeLists($param);
            $this->success('success', '', $campus, 0);
        }

        return $this->fetch();
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function room_edit()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $_data = input('post.');
            if (!$this->roomTimeValidate->scene('room_edit')->check($_data)) {
                $this->error($this->roomTimeValidate->getError(), null, '', 1);
            }
            $startTime = $_data['start_time'];
            $endTime = $_data['end_time'];
            $startTime = date("H:i", strtotime("$startTime +60 min"));
            if(strtotime($endTime) < strtotime($startTime)){
                $this->error('结束时间必须大于等于开始时间60分钟', null, '', 1);
            }
            $week = ClassTimeModel::get(['week'=>$_data['week']])['id'];
            $data['class_id'] = $_data['class_id'];
            $data['class_room'] = $_data['class_room'];
            $data['start_time'] = $_data['start_time'];
            $data['end_time'] = $_data['end_time'];
            $data['week'] = $week;
            $res = $this->classRoomTimeModel->save($data,['id'=>$_data['id']]);
            if (!$res) {
                $this->error('更新失败', null, '', 1);
            }
            $this->success('更新成功', '', '', 1);
        }
        return $this->fetch();
    }

    /**
     * 通过校区名称获取老师列表.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getById()
    {
        $time_slot_id = input('time_slot_id');
        if ($time_slot_id) {
            $teacher = $this->classTimeModel->getById($time_slot_id);
            $this->success('success', '', $teacher, 0);
        }
        $this->error('无数据');
    }

    /**
     * 删除.
     *
     * @return mixed
     */
    public function room_del()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {

            if (!$this->classRoomTimeModel->where(['id'=>input('id')])->delete()) {
                $this->error('删除失败', null, '', 1);
            }
            $this->success('删除成功', url('Campus/lists'), '', 1);
        }
    }


    /**
     * 更改校区状态.
     *
     * @return mixed
     */
    public function campus_status()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if($data['status'] == 1){
                $msg = '启用';
            }else{
                $msg = '禁用';
            }
            if (!$this->classTimeModel->save($data,['id'=>$data['id']])) {
                $this->error($msg.'校区失败', null, '', 1);
            }
            $this->success($msg.'成功', '', '', 1);
        }
    }

    /**
     * 计算时间差
     * @param int $timestamp1 时间戳开始
     * @param int $timestamp2 时间戳结束
     * @return array
     */
    function time_diff($timestamp1, $timestamp2)
    {
        if ($timestamp2 <= $timestamp1)
        {
            return ['hours'=>0, 'minutes'=>0, 'seconds'=>0];
        }
        $timediff = $timestamp2 - $timestamp1;
// 时
        $remain = $timediff%86400;
        $hours = intval($remain/3600);

// 分
        $remain = $timediff%3600;
        $mins = intval($remain/60);
// 秒
        $secs = $remain%60;

        $time = ['hours'=>$hours, 'minutes'=>$mins, 'seconds'=>$secs];

        return $time;
    }

    /**
     * 实例化.
     * @return bool|void
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->classTimeModel = new ClassTimeModel();
        $this->gradesModel = new GradesModel();
        $this->classRoomTimeModel = new ClassRoomTimeModel();
        $this->roomTimeValidate = new RoomTimeValidate();
        $this->campusModel = new CampusModel();
        $this->companyModel = new CompanyModel();
        $this->userModel = new UserModel();
    }
}
